package com.qulei.demo.db.utils;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

	private static final int VERSION = 1;
	private static final String DB_NAME = "demo.db";

	private List<DBObserver> observers = new ArrayList<DBObserver>();
	private boolean changed = false;

	private static DBHelper INSTANCE;

	public static DBHelper getInstance(Context context) {
		if (INSTANCE == null) {
			INSTANCE = new DBHelper(context);
		}
		return INSTANCE;
	}

	public void release() {
		this.clearObserver();
		this.getWritableDatabase().close();
		INSTANCE = null;
	}

	private DBHelper(Context context) {
		super(context, DB_NAME, null, VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		setChanged();
		notifyCreate(db);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		setChanged();
		notifyUpgrade(db, oldVersion, newVersion);
	}

	public void addObserver(DBObserver observer) {
		if (observer == null)
			return;
		synchronized (this) {
			if (!observers.contains(observer))
				observers.add(observer);
		}
	}

	public synchronized void deleteObserver(DBObserver observer) {
		observers.remove(observer);
	}

	public synchronized void clearObserver() {
		observers.clear();
	}

	public void notifyCreate(SQLiteDatabase db) {
		int size = 0;
		DBObserver[] arrays = null;
		synchronized (this) {
			if (hasChanged()) {
				clearChanged();
				size = observers.size();
				arrays = new DBObserver[size];
				observers.toArray(arrays);
			}
		}

		if (arrays != null) {
			for (DBObserver observer : arrays) {
				observer.onCreate(db);
			}
		}
	}

	public void notifyUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		int size = 0;
		DBObserver[] arrays = null;
		synchronized (this) {
			if (hasChanged()) {
				clearChanged();
				size = observers.size();
				arrays = new DBObserver[size];
				observers.toArray(arrays);
			}
		}
		if (arrays != null) {
			for (DBObserver observer : arrays) {
				observer.onUpgrade(db, oldVersion, newVersion);
			}
		}
	}

	protected void setChanged() {
		changed = true;
	}

	protected void clearChanged() {
		changed = false;
	}

	public boolean hasChanged() {
		return changed;
	}

}